<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\Coupon;
use app\common\model\CouponLog;
use app\common\model\Order;
use think\facade\Db;
use think\Exception;

class Pay extends Api
{

    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = '*';

    public function Pay(){
        $user=$this->auth->getUser();

        $order_id=request()->param('order_id',0);
        $coupon_id=request()->param('coupon_id',0);
        $type=request()->param('type','');

        $OM=new Order();

        if(!$user['user_wx_miniapp_openid'])
            $this->error('账号缺少openid');


        $order=$OM::get($order_id);

        if(!$order){
            $this->error('未找到订单信息');
        }
        if(!in_array($order['status'],[1])){
            $this->error('订单已经不是待支付状态');
        }
        if($order['user_id']!=$user['id']){
            $this->error('只可以支付自己的订单');
        }

        $order['pay_price']=$order['total_price'];
        if($coupon_id){
            $check_use=$OM->where('id','<>',$order['id'])
                ->where(['coupon_id'=>$coupon_id,'status'=>[2,3,4,5,6,7,15,41,42,43]])->count();

            if($check_use)
                $this->error('优惠券已被使用');

            $coupon=CouponLog::alias('CL')
                ->leftJoin('coupon C','CL.coupon_id=C.id')
                ->where(['CL.id'=>$coupon_id,'CL.user_id'=>$user['id']])
                ->field('C.*,CL.expire_time,CL.use_time')
                ->find()?:[];
            if(!$coupon)
                $this->error('优惠券不存在');
            if($coupon['expire_time']<time())
                $this->error('优惠券已过期');
            if($coupon['use_time']&&$order['coupon_id']!=$coupon_id)
                $this->error('优惠券已被其它待支付订单使用');

            if($coupon['start_money']>$order['total_price'])
                $this->error('订单金额未达到优惠券使用门槛');

            $order['pay_price']=bcsub($order['pay_price'],$coupon['discount_money'],2);
            $order['coupon_id']=$coupon_id;
            $order['coupon_price']=$order['pay_price']<0?$order['total_price']:$coupon['coupon_money'];
        }


        //回调链接
        $notifyurl = $this->request->root(true) . '/pay/notify/order_sn/' . $order['order_sn'];
        $returnurl = $this->request->root(true) . '/pay/notify/order_sn/' . $order['order_sn'];
        $response  = Service::submitOrder(
            $order['pay_price'],
            $order['order_sn'],
            'wechat',
            '支付订单',
            $notifyurl,
            $returnurl,
            'miniapp',
            $user['user_wx_miniapp_openid']
        );
        adlog('支付参数',$response);


        if($coupon_id)
            CouponLog::update(['use_time'=>time()],['id'=>$coupon_id]);

        $order->save();


        $this->success('获取支付参数成功',['response' => json_decode($response),'id' => $order['order_sn']]);
    }

    public function notify(){
        adlog('支付回调原本',file_get_contents("php://input"));
        $pay     = Service::checkNotify('wechat');
        if (!$pay) {
            echo '验签失败';
            return 'failed';
        }
        $data = $pay->verify();
        adlog('支付回调',$data);
        Db::startTrans();
        try {
            $order_sn   = request()->param('order_sn')?:'';
            $order      = Order::get(['order_sn' => $order_sn,'status' => 1]);
            if(!$order){
                throw new Exception('未找到对应订单');
            }
            if ($order) {
                // 改变订单状态
                $order['status']   = 2;
                $order['pay_time'] = time();
                $order->save();
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            //$this->error($e->getMessage());
            adlog('支付错误信息',$e->getMessage());
            exit;
        }
        return 'success';
    }
}